package com.wx.mall.sys.aspect;

import com.wx.mall.common.api.CommonResult;
import com.wx.mall.feign.LoginLogFeignClient;
import com.wx.mall.sys.component.JWTTokenUtil;
import com.wx.mall.sys.service.ILoginLogService;
import com.wx.mall.sys.utils.RequestHandlerUtil;
import com.wx.mall.common.vo.sys.LoginLogVO;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
@Aspect
public class LoginAspect {

    @Autowired
    private JWTTokenUtil jwtTokenUtil;
    @Autowired
    private RequestHandlerUtil requestHandler;
    @Autowired
    private ILoginLogService loginLogService;

    @Pointcut("execution(* com.wx.mall.sys.controller.LoginController.login(..) )")
    public void login() {
    }

    @Before("login()")
    public void before() {

    }

    @After("login()")
    public void after() {

    }

    @Around("login()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        // 登录日志VO
        LoginLogVO loginLog = new LoginLogVO();
        String username = null;

        //获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Object result = joinPoint.proceed();// 执行登录

        if (result instanceof CommonResult) {
            CommonResult commonResult = (CommonResult) result;
            Object data = commonResult.getData();// 获取结果中的封装数据
            if (data instanceof HashMap) {
                Map<String, String> map = (Map<String, String>) commonResult.getData();
                String token = map.get("token");// 获取token
                username = jwtTokenUtil.getUserNameFromToken(token);//根据token获取用户名
            }
        }

        if (username != null && !"".equals(username)) {
            requestHandler.init(request);
            loginLog.setLoginName(username);
            loginLog.setIp(requestHandler.getIPAddress());
            loginLog.setLocation(requestHandler.getRegion());
            loginLog.setBrowserName(requestHandler.getBrowser() + " - " + requestHandler.getOperatingSystem());
            loginLog.setLoginTime(new Date());
            loginLogService.save(loginLog);
        }

        return result;
    }
}
